package com.yst.webplugin.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class IPUtils {
    public static String getRealIp(HttpServletRequest request){
        List<String> ipList=new ArrayList<>();
        if (Objects.nonNull(request.getHeader("X-Real-IP"))){
            ipList.add(request.getHeader("X-Real-IP"));
        }

        String forward=request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(forward)){
            String[] ips=forward.split(",");
            ipList.addAll(Arrays.asList(ips));
        }

        if (Objects.nonNull((request.getRemoteAddr()))){
            ipList.add(request.getRemoteAddr());
        }

        if (!ipList.isEmpty()) {
            return ipList.get(0);
        }

        return "::::";
    }
}
